<template>
  <div>
    <div class="input-wrapper">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content wrapper" ref="wrapper" v-show="searchContentShow">
      <ul class="list-city-list">
        <li class="city-item border-bottom" v-for="item of list" :key="item.id"  @click="getSelectedCity(item.name)">{{item.name}}</li>
        <li class="city-item border-bottom" v-show="noDataShow">没有查询到相关数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
  name: 'Search',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    getSelectedCity (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    searchContentShow () {
      return this.keyword
    },
    noDataShow () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper)
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 200)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .input-wrapper
    height .5rem
    background $headerColor
    padding .1rem
    .search-input
      box-sizing: border-box
      width 100%
      height .5rem
      line-height .5rem
      text-align center
      color #666
      border-radius .1rem
      padding: 0 .1rem
  .search-content
    z-index 1
    position absolute
    top 1.5rem
    left 0
    right 0
    bottom 0
    overflow hidden
    background #ffffff
    .list-city-list
      padding .05rem .1rem
      .city-item
        font-size .3rem
        height .5rem
        line-height .5rem
</style>
